package org.fastsyncer.rest.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.ThirdpartyConstant;
import org.fastsyncer.common.entity.MappingTask;
import org.fastsyncer.common.entity.Page;
import org.fastsyncer.common.entity.RestResult;
import org.fastsyncer.common.util.ApplicationUtil;
import org.fastsyncer.common.util.JsonUtil;
import org.fastsyncer.core.service.ManagerService;
import org.fastsyncer.rest.common.ThridpartAppHandler;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/index")
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private ManagerService manager;

    @RequestMapping("")
    public String index(HttpServletRequest request, ModelMap model) {
        model.put("appId", request.getSession().getAttribute(ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_APP_APPID)));
        return "index/index";
    }

    @RequestMapping("/page/{opr}")
    public String driverAdd(HttpServletRequest request, ModelMap model, @PathVariable("opr") String opr, @RequestParam(value = "driverId", required = false) String driverId) {
        if (!StringUtils.isBlank(driverId)) {
            try {
                Object driver = manager.getDriver(driverId);
                model.addAttribute("dirver", driver);
                model.addAttribute("dirverJson", JsonUtil.objToJson(driver));
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e.getClass());
            }
        }
        return "index/" + opr;
    }

    @RequestMapping(value = "/getDriverAll")
    @ResponseBody
    public RestResult getDriverAll(HttpServletRequest request, String appId) {
        try {
            List<MappingTask> driverAll = manager.getDriverAll();
            // 取出第三方应用业务系统对应的驱动
            driverAll = ThridpartAppHandler.filter(request, driverAll, appId);
            return RestResult.restSuccess(driverAll);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail("获取驱动列表失败.");
        }
    }

    @RequestMapping(value = "/getDriver")
    @ResponseBody
    public RestResult getDriver(HttpServletRequest request, String appId, String driverName, int pageIndex, int pageSize) {
        try {
            List<MappingTask> driverAll = manager.getDriverAll();
            // 取出第三方应用业务系统对应的驱动
            driverAll = ThridpartAppHandler.filter(request, driverAll, appId);
            Page page = manager.getDriver(driverAll, driverName, pageIndex, pageSize);
            return RestResult.restSuccess(page);
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail("获取驱动列表失败.");
        }
    }

    @RequestMapping(value = "/getDriverLog")
    @ResponseBody
    public RestResult getDriverLog(HttpServletRequest request, @RequestParam(value = "driverId") String driverId) {
        try {
            return RestResult.restSuccess(manager.getDriverLog(driverId));
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail("获取驱动日志失败.");
        }
    }

    @RequestMapping(value = "/syncLogAll")
    @ResponseBody
    public RestResult syncLogAll(HttpServletRequest request, @RequestParam(value = "driverId") String driverId) {
        try {
            manager.syncDriverLogAll(driverId);
            return RestResult.restSuccess("同步所有日志成功.");
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail(e.getLocalizedMessage());
        }
    }

    @RequestMapping(value = "/syncLog")
    @ResponseBody
    public RestResult syncLog(HttpServletRequest request, @RequestParam(value = "msg") String msg) {
        try {
            manager.syncDriverLog(new JSONObject(msg));
            return RestResult.restSuccess("同步日志成功.");
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail(e.getLocalizedMessage());
        }
    }

    @RequestMapping(value = "/delLog")
    @ResponseBody
    public RestResult delLog(HttpServletRequest request, @RequestParam(value = "msg") String msg) {
        try {
            manager.delDriverLog(new JSONObject(msg));
            return RestResult.restSuccess("删除日志成功.");
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail(e.getLocalizedMessage());
        }
    }

    @RequestMapping(value = "/addLog")
    @ResponseBody
    public RestResult addLog(HttpServletRequest request, @RequestParam(value = "msg") String msg) {
        try {
            manager.addDriverLog(new JSONObject(msg));
            return RestResult.restSuccess("新增日志成功.");
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail("新增日志失败.");
        }
    }

    @RequestMapping("/download")
    public String download(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "dirverId") String id) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + id + ".txt");
        InputStream is = null;
        ServletOutputStream os = null;
        try {
            File log = manager.getDriverLogFile(id);
            if (log != null) {
                is = new FileInputStream(log);
                if (is != null) {
                    os = response.getOutputStream();
                    byte[] b = new byte[2048];
                    int length;
                    while ((length = is.read(b)) > 0) {
                        os.write(b, 0, length);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage(), e.getClass());
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

}
